package com.weacar.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.SystemUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.ToolsUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 忘记密码
 */


public class ForgetPasswordActivity extends BaseActivity {

    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.et_password_again)
    EditText et_password_again;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_vercode)
    EditText et_vercode;
    @BindView(R.id.tv_send_vercode)
    TextView tv_send_vercode;

    @OnClick({R.id.iv_back, R.id.iv_phone_clean, R.id.tv_send_vercode, R.id.tv_confirm})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_phone_clean:
                et_phone.setText("");
                break;
            case R.id.tv_send_vercode:
                if (ToolsUtil.isPhone(et_phone.getText().toString())) {
                    sendVerCode(et_phone.getText().toString().trim());
                } else {
                    ToastUtil.showShort(getApplicationContext(), "请输入正确的手机号");
                }
                break;
            case R.id.tv_confirm:
                setNewPassword();
                break;
        }
    }


    /**
     * 设置新密码
     */
    public void setNewPassword() {

        if (!ToolsUtil.isPhone(et_phone.getText().toString())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确的手机号");
            return;
        }

        if (et_vercode.getText().toString().trim().equals("")) {
            ToastUtil.showShort(getApplicationContext(), "验证码不能为空");
            return;
        }

        if (!ToolsUtil.isPassword(et_password.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "请输入正确格式的密码,6-8位字母和数字");
            return;
        }

        if (!et_password.getText().toString().trim().equals(et_password_again.getText().toString().trim())) {
            ToastUtil.showShort(getApplicationContext(), "2次输入的密码不一致");
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        try {
            showLoading("正在登录中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.forget_pwd_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("mobile", et_phone.getText().toString().trim());
            js_request.put("code", et_vercode.getText().toString().trim());
            js_request.put("newpwd", et_password.getText().toString().trim());


            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("Login_url =  " + params.getUri());
            LogUtils.d("login_params = " + params.getBodyContent());

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        ToastUtil.showShort(getApplicationContext(), "新密码设置成功,请登录");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 500);

                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getApplicationContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    // 验证码倒计时
    private CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            long time = millisUntilFinished / 1000;
            tv_send_vercode.setText(time + "秒后重新获取");
            tv_send_vercode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tv_send_vercode.setText("重新获取验证码");
            tv_send_vercode.setClickable(true);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarStyle("1");
        setContentView(R.layout.activity_forget_password);
        ButterKnife.bind(this);
        AppManager.getInstance().addActivity(this);
    }

    // 发送验证码
    public void sendVerCode(String phone) {

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        try {
            showLoading("正在发送中...");
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.vercode_url);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("mobile", phone);
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("url = " + params.getUri());
            LogUtils.d("params = " + params.getBodyContent());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        ToastUtil.showShort(getApplicationContext(), "验证码发送成功");
                        countDownTimer.start();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        // 销毁计时器
        countDownTimer.cancel();
        countDownTimer.onFinish();
        countDownTimer = null;
        super.onDestroy();
    }
}
